package com.example.gulimall.ware.exception;

import com.example.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *      商品服务全局异常拦截
 * </p>
 *
 * @author zyred
 * @since v 0.1
 **/
@Slf4j
@RestControllerAdvice
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerValidException (MethodArgumentNotValidException e) {
        e.printStackTrace();
        log.info("数据校验异常： {}， 异常类型：{}", e.getMessage(), e.getClass());

        Map<String, String> error = new HashMap<>();
        e.getBindingResult().getFieldErrors().forEach(
                a -> {
                    error.put(a.getField(), a.getDefaultMessage());
                }
        );

        return R.error(400, "参数校验失败").put("data", error);
    }


    @ExceptionHandler (value = Throwable.class)
    public R handlerException (Throwable t) throws Throwable {
        t.printStackTrace();
        return R.error(500, t.getMessage());
    }
}
